package com.apicloud.moduleWifiManager;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import com.uzmap.pkg.uzcore.UZWebView;
import com.uzmap.pkg.uzcore.annotation.UzJavascriptMethod;
import com.uzmap.pkg.uzcore.uzmodule.UZModule;
import com.uzmap.pkg.uzcore.uzmodule.UZModuleContext;

import android.content.Context;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.WifiLock;

public class ModuleWifi extends UZModule {
	public WifiManager wifiManager;
	public WifiInfo wifiInfo;
	public List<ScanResult> wifiList;
	public List<WifiConfiguration> wifiConfigurations;
	public WifiLock wifiLock;

	public ModuleWifi(UZWebView webView) {
		super(webView);
	}

	public void wifiAdminInit(Context context) {
		wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
		wifiInfo = wifiManager.getConnectionInfo();
	}

	public void openWifi() {
		if (!wifiManager.isWifiEnabled()) {
			wifiManager.setWifiEnabled(true);
		}
	}

	public void closeWifi() {
		if (wifiManager.isWifiEnabled()) {
			wifiManager.setWifiEnabled(false);
		}
	}

	public int checkState() {
		return wifiManager.getWifiState();
	}

	// wifiLock
	public void acquireWifiLock() {
		wifiLock.acquire();
	}

	// wifiLock
	public void releaseWifiLock() {
		if (wifiLock.isHeld()) { // �ж��Ƿ�����
			wifiLock.acquire();
		}
	}

	// wifiLock
	public void createWifiLock() {
		wifiLock = wifiManager.createWifiLock("wifiAdminLock");
	}

	public List<WifiConfiguration> getConfiguration() {
		return wifiConfigurations;
	}

	public void connetionConfiguration(int index) {
		if (index > wifiConfigurations.size()) {
			return;
		}

		wifiManager.enableNetwork(wifiConfigurations.get(index).networkId, true);
	}

	public void startScan() {
		wifiManager.startScan();
		wifiList = wifiManager.getScanResults();
		wifiConfigurations = wifiManager.getConfiguredNetworks();
	}

	public List<ScanResult> getWifiList() {
		return wifiList;
	}

	public String getMacAddress() {
		return (wifiInfo == null) ? "NULL" : wifiInfo.getMacAddress();
	}

	public String getBSSID() {
		return (wifiInfo == null) ? "NULL" : wifiInfo.getBSSID();
	}

	public int getIpAddress() {
		return (wifiInfo == null) ? 0 : wifiInfo.getIpAddress();
	}

	public int getNetWordId() {
		return (wifiInfo == null) ? 0 : wifiInfo.getNetworkId();
	}

	public int getNetWordId(String SSID) {
		startScan();
		for (int i = 0; i < wifiList.size(); i++) {
			if (wifiList.get(i).SSID == SSID) {
				return i;
			}
		}

		return -1;
	}

	public String getWifiInfo() {
		return (wifiInfo == null) ? "NULL" : wifiInfo.toString();
	}

	public boolean addNetWork(WifiConfiguration configuration) {
		int wcgId = wifiManager.addNetwork(configuration);
		return wifiManager.enableNetwork(wcgId, true);
	}

	public boolean removeNetWork(int netId) {
		if (netId > 0) {
			return wifiManager.removeNetwork(netId);
		}

		return false;
	}

	// 定义几种加密方式，WEP，WPA，没有密码
	public enum wifiCipherT {
		WIFICIPHER_WEP, WIFICIPHER_WPA, WIFICIPHER_NOPASS, WIFICIPHER_INVALID
	}

	/***
	 * 配置要连接的WIFI热点信息
	 * 
	 * @param SSID
	 * @param password
	 * @param type
	 *            加密类型
	 * @return
	 */
	public WifiConfiguration createWifiInfo(String SSID, String password, wifiCipherT type) {

		WifiConfiguration config = new WifiConfiguration();
		config.allowedAuthAlgorithms.clear();
		config.allowedGroupCiphers.clear();
		config.allowedKeyManagement.clear();
		config.allowedPairwiseCiphers.clear();
		config.allowedProtocols.clear();
		config.SSID = "\"" + SSID + "\"";

		// 增加热点时候 如果已经存在SSID 则将SSID先删除以防止重复SSID出现
		removeNetWork(getNetWordId(SSID));

		// 分为三种情况：没有密码 用wep加密 用wpa加密
		if (type == wifiCipherT.WIFICIPHER_NOPASS) { // WIFICIPHER_NOPASS
			config.wepKeys[0] = "";
			config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
			config.wepTxKeyIndex = 0;
		} else if (type == wifiCipherT.WIFICIPHER_WEP) { // WIFICIPHER_WEP
			config.hiddenSSID = true;
			config.wepKeys[0] = "\"" + password + "\"";
			config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
			config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
			config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
			config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
			config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
			config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
			config.wepTxKeyIndex = 0;
		} else if (type == wifiCipherT.WIFICIPHER_WPA) { // WIFICIPHER_WPA
			config.preSharedKey = "\"" + password + "\"";
			config.hiddenSSID = true;
			config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
			config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
			config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
			config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
			config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
			config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
			config.status = WifiConfiguration.Status.ENABLED;
		}

		return config;
	}

	/**
	 * <strong>函数</strong><br>
	 * <br>
	 * 该函数映射至Javascript中moduleWifi对象的add函数<br>
	 * <br>
	 * <strong>JS Example：</strong><br>
	 * moduleDataDocker.listWifiInfo(UZModuleContext context, function(ret,
	 * error){});
	 * 
	 * context = {}
	 * 
	 */
	@UzJavascriptMethod
	public List<JSONObject> jsget_listWifiInfo() {
		List<JSONObject> retJsons = new ArrayList<JSONObject>();

		wifiAdminInit(this.getContext());
		startScan();

		List<ScanResult> listWifi = getWifiList();
		if (listWifi != null) {
			for (int i = 0; i < listWifi.size(); i++) {
				JSONObject retJson = new JSONObject();

				ScanResult scanResult = listWifi.get(i);
				try {
					retJson.put("SSID", scanResult.SSID);
					retJson.put("BSSID", scanResult.BSSID);
					retJson.put("CAPA", scanResult.capabilities);
					retJson.put("SEQ", scanResult.level);
					retJson.put("FREQ", scanResult.frequency);
				} catch (JSONException e) {
					e.printStackTrace();
				}

				retJsons.add(retJson);
			}
		}

		return retJsons;
	}

	/**
	 * <strong>函数</strong><br>
	 * <br>
	 * 该函数映射至Javascript中moduleWifi对象的add函数<br>
	 * <br>
	 * <strong>JS Example：</strong><br>
	 * moduleDataDocker.addNetWork(UZModuleContext context, function(ret,
	 * error){});
	 * 
	 * context = {ap:ap, pwd:pwd, cipher:cipher}
	 * 
	 */
	@UzJavascriptMethod
	public void jsmethod_addNetWork(UZModuleContext context) {
		String ap = context.optString("ap"); // 热点
		String pwd = context.optString("pwd"); // 密码
		int cipher = context.optInt("cipher"); // 加密类型

		wifiCipherT wifiCipher;
		switch (cipher) {
		case 0:
			wifiCipher = wifiCipherT.WIFICIPHER_WEP;
			break;
		case 1:
			wifiCipher = wifiCipherT.WIFICIPHER_WPA;
			break;
		case 2:
			wifiCipher = wifiCipherT.WIFICIPHER_NOPASS;
			break;
		case 3:
			wifiCipher = wifiCipherT.WIFICIPHER_INVALID;
			break;
		default:
			wifiCipher = wifiCipherT.WIFICIPHER_WPA;
			break;
		}

		openWifi();
		jsget_listWifiInfo();

		WifiConfiguration wifiConfig = createWifiInfo(ap, pwd, wifiCipher);
		if (addNetWork(wifiConfig) == true) {
			context.success("true", false, true);
		} else {
			context.success("false", false, true);
		}
	}
}
